var md = angular.module('module_p-plugin', ['ng.ui']);
md.service('req', function($http, uiTips){
	this.get = function(url, data, cb){
		var httpParams = {url: url, method: 'GET'};

		if(!cb && angular.isFunction(data))
			cb = data;
		else
			httpParams.params = data;

		uiTips.loading();
		$http(httpParams).success(function(data){
			uiTips.unloading();

			if(data.error){
				uiTips.alert(data.error);
			}else{
				cb(data);
			}
		}).error(function(data){
			uiTips.unloading();

			uiTips.alert(data);
		});		
	};
});
md.controller('PluginCtrl', function($scope, $http, req, uiLog, uiTips, uiValid){
	$scope.list = [];
	$scope.query = {};
	$scope.ctrl = {};

	function getLocalAsMirror(){
		return document.location.protocol + '//' + document.location.host + '/wx/store/plugin';
	}

	// default mirror is current host
	$scope.query.mirror = getLocalAsMirror();

	var isUrlValid = function(url){
		return url && url.startsWith('http://'); 
	};

	var isMirrorLocal = function(){
		return $scope.query.mirror == getLocalAsMirror();
	};

	// get plugins from mirror
	$scope.search = function(){
		var mirror = $scope.query.mirror;
		if(!mirror || !isUrlValid(mirror)){
			$scope.ctrl.isShowMirror = true;
			$scope.ctrl.mirrorError = true;
			return;
		}

		$scope.ctrl.isShowMirror = false;
		$scope.ctrl.mirrorError = false;
		req.get(mirror + '/list', {q: $scope.query.q || ''}, function(data){
			var ll = data.ll;

			// check if any has already installed
			req.get('/wx/store/plugin/list-installed', function(data){
				if(!data.installed || !data.installed.list){
					$scope.list = ll;
					return;
				}

				_.each(ll, function(one){
					one.isInstalled = _.any(data.installed.list, function(it){
						return it.code == one.code && it.version == one.version;
					});
				});

				$scope.list = ll;
			});
		});
	};
	$scope.search();

	$scope.add = function(one){
		var params = {};

		if(!isMirrorLocal())
			params.mirror = $scope.query.mirror;

		params.code = one.code;
		params.version = one.version;

		req.get('/wx/store/plugin/install', params, function(data){
			if(data.flag){
				$scope.search();
			}else{
				uiTips.alert(data.msg);
			}
		});
	};

	$scope.del = function(one){
		var params = {};
		params.code = one.code;
		params.version = one.version;

		req.get('/wx/store/plugin/remove', params, function(data){
			if(data.flag){
				$scope.search();
			}else{
				uiTips.alert(data.msg);
			}
		});
	};
});